import { defineStore } from "pinia";

export const useRoleStore = defineStore("role", {
  state: () => ({
    // 角色列表---包含角色名称、继承的角色和权限
    roles: [
      {
        name: "superAdmin", // 超级管理员角色
        inherits: ["admin"], // 继承admin角色
        permissions: [], // 权限
      },
      {
        name: "admin",
        inherits: [],
        permissions: [
          "/dashboard",
          "/workbench",
          "/system/user",
          "/system/menu",
          "/system/role",
        ],
      },
    ],
  }),
  actions: {
    //获取所有权限
    getAllPermissions(roleName) {
      const role = this.roles.find((r) => r.name === roleName);
      if (!role) return [];
      const inheritedPerms = role.inherits.flatMap((r) =>
        this.getAllPermissions(r)
      );
      return [...new Set([...role.permissions, ...inheritedPerms])];
    },
    //更新角色
    async updateRole(role) {
      const index = this.roles.findIndex((r) => r.name === role.name);
      if (index >= 0) {
        this.roles.splice(index, 1, role);
      } else {
        this.roles.push(role);
      }
    },
    //删除角色
    async deleteRole(name) {
      this.roles = this.roles.filter((r) => r.name !== name);
    },
  },
});
